import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:chatbot/liaotian.dart';
import 'package:chatbot/yanses.dart';
import 'package:chatbot/chuangzuo_yemian.dart';
import 'package:chatbot/shuju_guanli.dart';
import 'package:chatbot/shijian.dart';
import 'package:chatbot/shijian_bashi.dart';
import 'package:chatbot/wode_yemain.dart';
import 'package:chatbot/chanpin_guanli.dart';
import 'package:chatbot/juse_yemian.dart';
import 'package:chatbot/fenxiang_shuju.dart';
import 'package:chatbot/utils.dart';
import 'package:chatbot/huiyuan_yemian.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keychain/flutter_keychain.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_review/in_app_review.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:speech_to_text/speech_to_text_provider.dart';

import 'cunchu_guanli.dart';

void main() {
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
  chushihua();
}

chushihua() async {
  QingQiuGuanLi.instance;
  await BenDiCunchu.init();
  if (CunChuGuanLi.getUID() == null) {
    var savedUid = await FlutterKeychain.get(key: "uidV3");

    if (savedUid == null) {
      String uid = "${DateTime.now().millisecondsSinceEpoch ~/ 1000}";
      CunChuGuanLi.putUID(uid);
      await FlutterKeychain.put(key: "uidV3", value: uid);
    } else {
      CunChuGuanLi.putUID(savedUid);
    }
  }

  runApp(const ZhuAPP());
}

class ZhuAPP extends StatelessWidget {
  const ZhuAPP({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Yanse.jibenYanse),
        primaryColor: Yanse.jibenYanse,
        dialogBackgroundColor: Colors.white,
        primaryTextTheme:
            const TextTheme(bodyLarge: TextStyle(color: Colors.black)
                // etc...
                ),
      ),
      builder: BotToastInit(),
      //1. call BotToastInit
      navigatorObservers: [BotToastNavigatorObserver()],
      //2. re
      home: WoDeJiaYemian(),
    );
  }
}

class WoDeJiaYemian extends StatefulWidget {
  const WoDeJiaYemian({super.key});

  @override
  State<WoDeJiaYemian> createState() => _WoDeJiaYemianState();
}

class _WoDeJiaYemianState extends State<WoDeJiaYemian>
    with TickerProviderStateMixin {
  late TabController _biaoqianKongzhi;
  late StreamSubscription dingyue;
  late SpeechToTextProvider speechProvider;
  var quxiao;
  final SpeechToText shuohua = SpeechToText();
  late StreamSubscription<dynamic> _dingyue;
  List biaoqian = ["对话", "创作", "角色"];
  late List<Widget> haizi;

  @override
  void initState() {
    dingyue = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
      if (result == ConnectivityResult.mobile ||
          result == ConnectivityResult.wifi) {
        ChanPinGuanli.instance.huoquCHanpin();
        zhuce();
        shiFouGUoqi();
      }
    });
    final Stream purchaseUpdated = InAppPurchase.instance.purchaseStream;
    _dingyue = purchaseUpdated.listen((purchaseDetailsList) {
      jiantingDingyueGEgnxin(purchaseDetailsList);
    }, onDone: () {
      _dingyue.cancel();
    }, onError: (error) {
      // handle error here.
    });
    _biaoqianKongzhi = TabController(length: biaoqian.length, vsync: this);
    speechProvider = SpeechToTextProvider(shuohua);
    super.initState();

    speechProvider.initialize();
    haizi = [
      LiaotianYemian(
        tishiCi: CunChuGuanLi.huoquShouyeJuese(),
        jueseMing: CunChuGuanLi.shouyeJueseMing(),
        jueseTishi: CunChuGuanLi.shouyeJueseTishi(),
        leixing: -1,
        tishiTou: "向AI提问",
        shuoHua: shuohua,
        kouyuTiGong: speechProvider,
      ),
      ChuangzaoBiaoqianYemian(
        shuohua: shuohua,
        shuahuatigong: speechProvider,
      ),
      JuseBiaoQianYemian(shuohua: shuohua, shuohuaTigong: speechProvider),

      // MinePage()
    ];
  }

  shiFouGUoqi() async {
    if (!CunChuGuanLi.isVip()) {
      await InAppPurchase.instance.restorePurchases();
    }
  }

  void jiantingDingyueGEgnxin(List<PurchaseDetails> qingyueXiangqingLiebiao) {
    debugPrint("_listenToPurchaseUpdated!!!!");

    qingyueXiangqingLiebiao.forEach((PurchaseDetails purchaseDetails) async {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        BotToast.showLoading();
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          Utils.xianshiTishi("支付失败");
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          if (purchaseDetails.transactionDate != null) {
            if (purchaseDetails.productID ==
                ChanPinGuanli.instance.kIds.elementAt(0)) {
              // DateTime.now().millisecondsSinceEpoch
              //周订阅
              int transactionDate =
                  int.parse(purchaseDetails.transactionDate!); //毫秒
              int expireDate = transactionDate + 7 * 24 * 60 * 60 * 1000;
              if (expireDate > CunChuGuanLi.guoqishijian()) {
                CunChuGuanLi.cunGuoqisj(expireDate);
                CunChuGuanLi.cunDingyueJg(
                    "${ChanPinGuanli.instance.huoquzhou().rawPrice}");
              }
              debugPrint("transactionDate week!!!!=$transactionDate");
            } else if (purchaseDetails.productID ==
                ChanPinGuanli.instance.kIds.elementAt(1)) {
              //月订阅
              int transactionDate =
                  int.parse(purchaseDetails.transactionDate!); //毫秒
              int expireDate = transactionDate + 31 * 24 * 60 * 60 * 1000;
              if (expireDate > CunChuGuanLi.guoqishijian()) {
                CunChuGuanLi.cunGuoqisj(expireDate);
                CunChuGuanLi.cunDingyueJg(
                    "${ChanPinGuanli.instance.huoquYue().rawPrice}");
              }
              debugPrint("transactionDate month!!!!=$transactionDate");
            } else if (purchaseDetails.productID ==
                ChanPinGuanli.instance.kIds.elementAt(2)) {
              //年订阅
              int transactionDate =
                  int.parse(purchaseDetails.transactionDate!); //毫秒
              int expireDate = transactionDate + 365 * 24 * 60 * 60 * 1000;
              if (expireDate > CunChuGuanLi.guoqishijian()) {
                CunChuGuanLi.cunGuoqisj(expireDate);
                CunChuGuanLi.cunDingyueJg(
                    "${ChanPinGuanli.instance.huoquNian().rawPrice}");
              }
              debugPrint("transactionDate year!!!!=$transactionDate");
            }
          }
          if (purchaseDetails.status == PurchaseStatus.purchased) {
            Utils.xianshiTishi("支付成功");
            Future.delayed(const Duration(milliseconds: 1000), () {
              ShijianGUanli.instance.shijianChe.fire(DingyueSHijian());
            });
            setState(() {});
          }
          debugPrint("restored!!!!${purchaseDetails.transactionDate}");
        } else if (purchaseDetails.status == PurchaseStatus.canceled) {
          Utils.xianshiTishi("支付取消");
        } else {
          if (quxiao != null) {
            quxiao();
          }
        }
        if (purchaseDetails.pendingCompletePurchase) {
          await InAppPurchase.instance.completePurchase(purchaseDetails);
        }
      }
    });
    haoping();
  }

  haoping() async {
    final InAppReview inAppReview = InAppReview.instance;
    if (await inAppReview.isAvailable()) {
      inAppReview.requestReview();
    }
  }

  @override
  void dispose() {
    super.dispose();
    _dingyue.cancel();
    dingyue.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Yanse.qianse,
      appBar: PreferredSize(
          preferredSize: Size.fromHeight(40.0),
          child: SafeArea(
              child: Row(
            children: [
              Container(
                width: 12,
              ),
              CunChuGuanLi.isVip()
                  ? Container()
                  : InkWell(
                      highlightColor: Colors.transparent, // 透明色
                      splashColor: Colors.transparent, // 透明色
                      onTap: () {
                        Navigator.push(context,
                            CupertinoPageRoute(builder: (BuildContext context) {
                          return HuiYuanYeMian("我的");
                        }));
                      },
                      child: Image.asset(
                        'assets/images/vip_icon.png',
                        width: 26,
                        height: 26,
                        fit: BoxFit.cover,
                      )),
              Expanded(child: Container()),
              TabBar(
                isScrollable: true,
                unselectedLabelColor: Color(0xff848691),
                labelStyle: TextStyle(
                    color: Colors.black,
                    fontSize: 17,
                    fontWeight: FontWeight.w600),
                unselectedLabelStyle:
                    const TextStyle(fontSize: 17, fontWeight: FontWeight.w600),
                dividerColor: Yanse.shense,
                indicatorColor: Colors.white,
                controller: _biaoqianKongzhi,
                tabs: biaoqian.map((e) => Tab(text: e, height: 40)).toList(),
              ),
              Expanded(child: Container()),
              InkWell(
                  highlightColor: Colors.transparent, // 透明色
                  splashColor: Colors.transparent, // 透明色
                  onTap: () {
                    Navigator.push(context,
                        CupertinoPageRoute(builder: (BuildContext context) {
                      return WodeYemian();
                    }));
                  },
                  child: Image.asset(
                    'assets/images/mine.png',
                    width: 24,
                    height: 24,
                    color: Colors.black,
                    fit: BoxFit.contain,
                  )),
              Container(
                width: 12,
              )
            ],
          ))),
      body: TabBarView(
        //构建
        controller: _biaoqianKongzhi,
        children: biaoqian.map((e) {
          if (e == biaoqian[1]) {
            return haizi[1];
          } else if (e == biaoqian[2]) {
            return haizi[2];
          }
          {
            return haizi[0];
          }
        }).toList(),
      ),
    );
  }

  void zhuce() {
    if (!CunChuGuanLi.shifouzhuce()) {
      CunChuGuanLi.shezhizhuce();
      QingQiuGuanLi.instance.zhuoce();
    }
  }
}
